package com.letianpai.common.client;

import com.letianpai.common.server.BackInfo;
import com.letianpai.common.server.Constants;
import com.letianpai.common.server.ResultBean;
import com.letianpai.common.tool.FileUtil;
import com.letianpai.common.tool.ImageTool;
import com.letianpai.db.entity.PictureInfo;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2014/9/29.
 */
public class HttpFileUploadClient {
    public static <T> ModelResult<T> doVeryLongPost(String head, Map<String, String> params, List<PictureInfo> picList) {
        HttpClient httpClient = null;
        ModelResult<T> modelResult = new ModelResult<T>();
        List<String> thumbnail_list = new ArrayList<String>();
        try {
            MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
            int count = picList.size();
            for (int i = 0; i < count; i++) {
                PictureInfo pic = picList.get(i);
                int number = i + 1;
                StringBody parType = new StringBody(pic.getPicType(), ContentType.TEXT_PLAIN);
                StringBody parMd5 = new StringBody(pic.getPicMd5(), ContentType.TEXT_PLAIN);
                // 创建缩略图
                String file_path = CommonTool.PROJECT_TEMP_PATH + "/" + UUID.randomUUID().toString() + "." + pic.getPicType();
                boolean result = ImageTool.createThumbnail(pic.getPicPath(), file_path);
                if (result) {
                    File file = new File(file_path);
                    if (file.exists()) {
                        thumbnail_list.add(file_path);
                        reqEntity.addPart("fmd5" + number, parMd5);
                        reqEntity.addPart("suffix" + number, parType);
                        FileBody fileBody = new FileBody(new File(file_path));
                        reqEntity.addPart("photo" + number, fileBody);
                    }
                }
            }
            JSONObject parentJson = new JSONObject();
            parentJson.put("head", head);
            JSONObject childJson = new JSONObject();
            for (String key : params.keySet()) {
                childJson.put(key, params.get(key));
            }
            parentJson.put("content", childJson);
            StringBody parType = new StringBody(parentJson.toString(), ContentType.TEXT_PLAIN);
            reqEntity.addPart("msg", parType);
//            String url = Constants.URL + "?msg=" + parentJson.toString();
            HttpPost httpPost = new HttpPost(Constants.URL);
            //http://www.open-open.com/lib/view/open1327556868217.html
            httpPost.setEntity(reqEntity.build());
            HttpParams httpParameters = new BasicHttpParams();
                    /* 从连接池中取连接的超时时间 */
            ConnManagerParams.setTimeout(httpParameters, 6000000);
            // 连接超时
            HttpConnectionParams.setConnectionTimeout(httpParameters, 6000000);
            //// 超时设置
            HttpConnectionParams.setSoTimeout(httpParameters, 6000000);
            httpClient = new DefaultHttpClient(httpParameters);
            HttpResponse response = httpClient.execute(httpPost);
            modelResult.setCode(response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity());
                BackInfo backInfo = new BackInfo(result);
                modelResult.setMessage(backInfo.getMessage());
                if ("SUCCESS".equals(backInfo.getStatus())) {
                    modelResult.setReturnResult(true);
                } else {
                    modelResult.setReturnResult(false);
                }
                //{"message":"成功","data":{},"status":"SUCCESS"}
                modelResult.setMessage(backInfo.getData());
            } else {
                modelResult.setReturnResult(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            modelResult.setReturnResult(false);
        } finally {
//            FileUtil.deleteTempFileList(thumbnail_list);
            httpClient.getConnectionManager().shutdown();
        }
        return modelResult;
    }
}
